<?php
namespace Common\Model;

use Think\Model;

class ChannelRecommendModel extends  CommonModel {

	public $tableName = 'channel_recommend';



	//添加渠道推荐信息
	public function channel_recommend_save($openid,$channel_id = 0){
		$create_date = date('Y-m-d');
		$where = [
			'openid' 	  => $openid,
			'create_date' => $create_date
		];
		$info = $this->where($where)->find();
		if(empty($info)){
			$data = [
				'channel_id'  => $channel_id?$channel_id:0,
				'openid'      => $openid,
				'create_date' => $create_date,
				'create_time' => time()
			];
			$this->add($data);
		}
		return true;
	}



	//渠道推荐列表
	public function get_channel_recommend_list(array $params){
		$start_time = strtotime($params['date'][0]);
		$end_time  = strtotime($params['date'][1]);
		$fields = $date_list = [];
		$date_list = [];
		while ($start_time <= $end_time) {
			$date       = date('Y-m-d', $start_time);
			$month_date = date('m-d', $start_time);
			$fields[] = "SUM(CASE WHEN a.create_date = '{$date}' THEN 1 ELSE 0 END) AS '{$month_date}'";
			$date_list[] = $month_date;
			$start_time += 86400;
		}

		$where = [
			'a.create_date' => [['EGT', $params['date'][0]], ['ELT', $params['date'][1]]]
		];
		$params['pid']?$where["b.pid"]=$params['pid']:"";

		$field = "a.channel_id,IFNULL(b.channel_name,'其他') as channel_name,IFNULL(c.channel_name,'其他') as pid_channel_name," . join(',', $fields);

		$list = $this
			->alias("a")
			->field($field)
			->where($where)
			->join("LEFT JOIN tp_channel b ON b.id = a.channel_id")
			->join("LEFT JOIN tp_channel c ON c.id = b.pid")
			->group("a.channel_id,b.channel_name,c.channel_name")
			->order("a.channel_id DESC")
			->select();
		$result = ['date_list' => $date_list,'list'=>$list];
		return $result;
	}

}

?>
